
const Service = require('egg').Service;
const jwt = require('jsonwebtoken')

// egg-validate
class HomeService extends Service {
  async login() {
    // 定义创建接口的请求参数规则
    const createRule = {
      skuid: { type: 'string', required: true },
      password: { type: 'string', required: true },
    };
    this.ctx.validate(createRule, this.ctx.request.body);
    const { skuid, password } = this.ctx.request.body;
    // let pwd = this.ctx.helper.getPassword(password)
    // 校验 `ctx.request.body` 是否符合我们预期的格式
    // 如果参数校验未通过，将会抛出一个 status = 422 的异常
    const data = await this.app.mysql.select('users', {
      where: {
        skuid,
        password
      }
    })
    const token = jwt.sign({ ...data[0] }, this.app.config.keys, { expiresIn: '24h' })
    if (data.length) {
      return { code: 0, msg: 'success', token }
    } else {
      return { code: -1, msg: 'fail' }
    }
  }

  async register() {
    const { skuid, username, password, userid } = this.ctx.request.body;
    let pwd = this.ctx.helper.getPassword(password)
    const data = await this.app.mysql.select('users', {
      where: {
        skuid,
        password: pwd,
        userid
      }
    })
    if (data.length) {
      return { code: -1, msg: 'fail' }
    } else {
      const data = await this.app.mysql.insert('users', {
        skuid,
        username,
        password: pwd,
        userid
      })
      if (data.insertId) {
        return { code: 0, msg: 'success', id: data.insertId }
      } else {
        return { code: -1, msg: 'fail' }
      }
    }
  }

  async add() {
    const { skuid, username, skill, theory } = this.ctx.request.body;
    const data = await this.app.mysql.insert('score', {
      skuid, username, skill, theory
    })
    if (data.insertId) {
      return { code: 0, msg: 'success', insertId: data.insertId }
    } else {
      return { code: -1, msg: 'fail' }
    }
  }
}

module.exports = HomeService